package com.terrace.web.tagext.easyui.support;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.terrace.core.utils.JsonUtils;
import com.terrace.web.exception.CustomTagException;
import com.terrace.web.tagext.easyui.utils.EasyUIUtils;

/**
 * easyui的基本标签
 * @author jiangyg
 *
 */
public class BaseTagSupport extends TagSupport {
	
	private static final long serialVersionUID = -2638454032631065521L;
	
	/**
	 * easyui属性扩展，json格式
	 */
	protected String expands;
	
	/**
	 * 标签属性扩展，json格式
	 */
	protected String attributes;
	
	/**
	 * 把easyui扩展的属性转化成字符串
	 * @return
	 */
	protected String transferExtensionForStr() {
		StringBuffer sb = new StringBuffer();
		if (StringUtils.isNotBlank(expands)) {
			try {
				Map<String, Object> extensions = JsonUtils.jsonToBean(expands, new TypeReference<Map<String, Object>>() {});
				Set<Entry<String, Object>> entrySet = extensions.entrySet();
				for (Entry<String, Object> entry : entrySet) {
					EasyUIUtils.appendDatsOption(sb, entry.getKey(), entry.getValue());
				}
				EasyUIUtils.substringLastComma(sb);
			} catch (IOException e) {
				throw new CustomTagException("自定义标签，扩展属性[" + expands + "]解析失败。");
			}
		}
		return sb.toString();
	}
	
	/**
	 * 把标签属性扩展转化成字符串
	 * @return
	 */
	protected String transferAttributesForStr() {
		StringBuffer sb = new StringBuffer();
		if (StringUtils.isNotBlank(attributes)) {
			try {
				Map<String, Object> extensions = JsonUtils.jsonToBean(attributes, new TypeReference<Map<String, Object>>() {});
				Set<Entry<String, Object>> entrySet = extensions.entrySet();
				for (Entry<String, Object> entry : entrySet) {
					sb.append(entry.getKey() + "=\"" + entry.getValue() + "\" ");
				}
			} catch (IOException e) {
				throw new CustomTagException("自定义标签，标签属性[" + attributes + "]解析失败。");
			}
		}
		return sb.toString();
	}

	public String getExpands() {
		return expands;
	}

	public void setExpands(String expands) {
		this.expands = expands;
	}

	public String getAttributes() {
		return attributes;
	}

	public void setAttributes(String attributes) {
		this.attributes = attributes;
	}

}
